;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Stock.PurchaseIn", [])
        .controller("PurchaseInCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.submitted = false;
            $scope.markInfo = {
                allChecked: false,
                addAllChecked: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.markInfoDetail = {
                allChecked: false,
                addAllChecked: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.billPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.orderCondition = {};
            var selectedOrder = [];
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.dataList = [];
            $scope.purchaseBillList = [];
            $scope.detailInfo = {
                headerInfo: {},
                detailList: []
            };
            $scope.steps = {
                curStep: 0,
                list: [{ name: '选择采购订单' }, { name: '生成采购入库单' }]
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/purchaseInbound/export"),
                sectionParam: { ids: [] },
                allUrl: ybHttp.RequestUrl("device", "/purchaseInbound/exportAll")
            };
            $scope.warehouseList = [];
            $scope.tableConfig = {
                fixedWidth: 220,
                scrollWidth: 1090,
                tableCol: [
                    {
                        type: "",
                        name: "采购入库单号",
                        dataField: "purchaseInboundOrder",
                        width: 170,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购订单号",
                        dataField: "purchaseRequestOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调入仓库",
                        dataField: "warehouseCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "入库状态",
                        dataField: "outLocationStatusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 180,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.purchaseBillTbConf = {
                scrollWidth: 830,
                tableCol: [
                    {
                        type: "",
                        name: "采购单号",
                        dataField: "billNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供货商名称",
                        dataField: "supplierOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购方式",
                        dataField: "typeDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发运方式",
                        dataField: "shippingMethod",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 80,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.newByTbConf = {
                scrollWidth: 1000,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件简号",
                        width: 120,
                        dataField: "materialsShortNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件英文名",
                        width: 150,
                        dataField: "materialsDesEn",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "采购数量",
                        width: 100,
                        dataField: "qty",
                        input: true,
                        inputType: "qtyFlag"
                    },
                    {
                        name: "入库数量",
                        width: 120,
                        dataField: "amount",
                        input: true,
                        inputType: "amountFlag"
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                ]
            };
            $scope.newTbConf = {
                scrollWidth: 1000,
                tableCol: [
                    {
                        name: "采购订单号",
                        width: 200,
                        dataField: "purchaseRequestOrder",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库数量",
                        width: 120,
                        dataField: "amount",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "订单总数",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已发数量",
                        width: 100,
                        dataField: "sendQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "可入库数量",
                        width: 100,
                        dataField: "canInQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "行号",
                        width: 100,
                        dataField: "rowNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                ]
            };
            $scope.editTbConf = {
                scrollWidth: 1120,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件简号",
                        width: 120,
                        dataField: "materialsShortNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件英文名",
                        width: 150,
                        dataField: "materialsDesEn",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "采购数量",
                        width: 100,
                        dataField: "qty",
                        input: true,
                        inputType: "qtyFlag"
                    },
                    {
                        name: "入库数量",
                        width: 120,
                        dataField: "amount",
                        input: true,
                        inputType: "amountFlag"
                    },
                    {
                        name: "实际入库数量",
                        width: 120,
                        dataField: "realAmount",
                    },
                    {
                        name: "入库状态",
                        width: 100,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                ]
            };
            $scope.detailTbConf = {
                scrollWidth: 1080,
                tableCol: [
                    {
                        name: "序号",
                        dataField: "rownum",
                        width: 80,
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                    },
                    {
                        name: "零件简号",
                        width: 120,
                        dataField: "materialsShortNo",
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialName",
                    },
                    {
                        name: "零件英文名",
                        width: 150,
                        dataField: "materialsDesEn",
                    },
                    {
                        name: "采购数量",
                        width: 100,
                        dataField: "qty",
                    },
                    {
                        name: "入库数量",
                        width: 120,
                        dataField: "amount",
                    },
                    {
                        name: "实际入库数量",
                        width: 110,
                        dataField: "realAmount",
                    },
                    {
                        name: "入库状态",
                        width: 100,
                        dataField: "statusShow",
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                    },
                ]
            };
            $scope.inTbConf = {
                scrollWidth: 1160,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                    },
                    {
                        name: "零件简号",
                        width: 120,
                        dataField: "materialsShortNo",
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialName",
                    },
                    {
                        name: "零件英文名",
                        width: 150,
                        dataField: "materialsDesEn",
                    },
                    {
                        name: "采购数量",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库数量",
                        width: 120,
                        dataField: "amount",
                        input: false,
                        inputType: "num"
                    },
                    {
                        name: "储位",
                        width: 150,
                        dataField: "locationCode",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "入库状态",
                        width: 100,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                ]
            };
            $scope.tabFlag = {};
            $scope.inState = [
                { id: 0, name: "未入库" },
                { id: 1, name: "部分入库" },
                { id: 2, name: "已入库" },
                { id: 3, name: "强制结单" }
            ];
            var btnPermissionCode = {
                purchaseInAdd: window.ActionCode.purchaseInAdd,
                purchaseInEdit: window.ActionCode.purchaseInEdit,
                purchaseInDel: window.ActionCode.purchaseInDel,
                purchaseInIn: window.ActionCode.purchaseInIn,
                purchaseInExport: window.ActionCode.purchaseInExport,
                purchaseInPrint: window.ActionCode.purchaseInPrint,
                mandatoryFinish: window.ActionCode.purchaseInMandatoryFinish,
                purchaseInSAP: window.ActionCode.purchaseInSAP,
                purchaseInReceipt: window.ActionCode.purchaseInReceipt,
                purchaseInRevoke: window.ActionCode.purchaseInRevoke
            };

            $scope.btnPermission = {
                purchaseInAdd: true,
                purchaseInEdit: true,
                purchaseInDel: true,
                purchaseInIn: true,
                purchaseInExport: true,
                purchaseInPrint: true,
                mandatoryFinish: true,
                purchaseInSAP: true,
                purchaseInReceipt: true,
                purchaseInRevoke: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: { left: $scope.tableConfig.fixedWidth + "px" },
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        if ($scope.warehouseList.length === 0) {
                            getWarehouse();
                        }
                        break;
                    case 2:
                        if ($scope.warehouseList.length === 0) {
                            getWarehouse();
                        }
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };


            function initData() {
                $scope.detailInfo = {
                    headerInfo: {},
                    detailList: []
                };
                $scope.toolbarConfig.showMateriel = false;
                $scope.steps.curStep = 0;
                $scope.tabFlag = {};
                $scope.isImportAdd = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allChecked: false,
                    addAllChecked: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.selectedIds = [];
                var service = "device";
                var reqUrl = "/purchaseInbound/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                param.filters.isProcessing = null;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
                        item.outLocationStatusShow = $filter("ProgressStatus")(item.status, "inDepot");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.toSort = function (config, index) {
                return;
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "viewSapError":
                        viewSapError(item);
                        break;
                    default:
                        break;
                }
            };

            function viewSapError(item) {
                ybWidget.ShowMessage(item.sapErrorMsg, MESG_TYPE.Note);
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = { seller: false, unInboundFlag: 0, dateRange: null };
            };

            function geBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function selectOrder(item) {
                if (angular.isDefined(item)) {
                    if (!!item.isChecked) {
                        selectedOrder.push(item);
                    } else {
                        for (var p = selectedOrder.length - 1; p >= 0; p--) {
                            if (item.billId === selectedOrder[p].billId) {
                                selectedOrder.splice(p, 1);
                                break;
                            }
                        }
                    }
                } else {
                    if (!!$scope.markInfo.addAllChecked && selectedOrder.length === 0) {
                        selectedOrder = angular.copy($scope.purchaseBillList);
                        return
                    }
                    for (var i = 0, len = $scope.purchaseBillList.length; i < len; i++) {
                        var existed = false;
                        if (!!$scope.purchaseBillList[i].isChecked) {
                            for (var j = 0, lenJ = selectedOrder.length; j < lenJ; j++) {
                                if ($scope.purchaseBillList[i].billId === selectedOrder[j].billId) {
                                    existed = true;
                                    break;
                                }
                            }
                            if (!existed) {
                                selectedOrder.push($scope.purchaseBillList[i]);
                            }
                        } else {
                            for (var l = selectedOrder.length - 1; l >= 0; l--) {
                                if ($scope.purchaseBillList[i].billId === selectedOrder[l].billId) {
                                    selectedOrder.splice(l, 1);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            $scope.selectSingle = function (item, type) {
                var checkFlag = "";
                if (type === "") {
                    checkFlag = "allChecked"
                } else if (type === "add") {
                    checkFlag = "addAllChecked";
                    selectOrder(item);
                } else if (type === "del") {
                    checkFlag = "allCheckedMaterial";
                }

                if (!item.isChecked) {
                    $scope.markInfo[checkFlag] = false;
                } else {
                    if (!checkAll(type)) {
                        $scope.markInfo[checkFlag] = false;
                    } else {
                        $scope.markInfo[checkFlag] = true;
                    }
                }
                geBillIds();
            };

            function checkAll(type) {
                var tempList = "";
                var selectAll = false;
                if (type === "") {
                    tempList = $scope.dataList;
                } else if (type === "add") {
                    tempList = $scope.purchaseBillList;
                } else if (type === "del") {
                    tempList = $scope.detailInfo.detailList;
                }

                for (var i = 0, len = tempList.length; i < len; i++) {
                    if (!tempList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (type) {
                var tempList = "";
                var checkFlag = "";
                if (type === "") {
                    tempList = $scope.dataList;
                    checkFlag = 'allChecked';
                } else if (type === "add") {
                    tempList = $scope.purchaseBillList;
                    checkFlag = 'addAllChecked';
                } else if (type === "del") {
                    tempList = $scope.detailInfo.detailList;
                    checkFlag = 'allCheckedMaterial';
                }

                for (var i = 0, len = tempList.length; i < len; i++) {
                    tempList[i].isChecked = $scope.markInfo[checkFlag];
                }

                if (type === "add") {
                    selectOrder();
                }

                geBillIds();
            };

            // 详情页明细列表勾选相关 ---start---
            $scope.selectedIds = [];
            $scope.selectDetailSingle = function (item, type) {
                var checkFlag = "";
                if (type === "") {
                    checkFlag = "allChecked"
                }

                if (!item.isChecked) {
                    $scope.markInfoDetail[checkFlag] = false;
                } else {
                    if (!checkDetailAll(type)) {
                        $scope.markInfoDetail[checkFlag] = false;
                    } else {
                        $scope.markInfoDetail[checkFlag] = true;
                    }
                }
                geBillDetailIds();
            };

            function checkDetailAll(type) {
                var tempList = "";
                var selectAll = false;
                if (type === "") {
                    tempList = $scope.detailInfo.detailList;
                }

                for (var i = 0, len = tempList.length; i < len; i++) {
                    if (!tempList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectDetailAll = function (type) {
                var tempList = "";
                var checkFlag = "";
                if (type === "") {
                    tempList = $scope.detailInfo.detailList;
                    checkFlag = 'allChecked';
                }
                for (var i = 0, len = tempList.length; i < len; i++) {
                    tempList[i].isChecked = $scope.markInfoDetail[checkFlag];
                }

                geBillDetailIds();
            };

            function geBillDetailIds() {
                $scope.selectedIds = [];
                angular.forEach($scope.detailInfo.detailList, function (item) {
                    if (!!item.isChecked && !$scope.selectedIds.includes(item.materialNo)) {
                        $scope.selectedIds.push(item.materialNo);
                        $scope.selectedIds = [...new Set($scope.selectedIds)];
                    }
                });
            }
            // 详情页明细列表勾选相关 ---end---



            $scope.addByPurchaseOrder = function () {
                $scope.tabFlag.type = 0;
                $scope.markInfo = {
                    allChecked: false,
                    addAllChecked: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                selectedOrder = [];
                getPurchaseBill(1);
                $scope.changeTab(1);
            };

            function getWarehouse() {
                var service = "device";
                var reqUrl = "/warehouse/listWarehouses";
                var param = { pageNum: 0, pageSize: 0 };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.warehouseList = resp.value.list;
                })
            }

            function checkRowSelected() {
                for (var i = 0, len = selectedOrder.length; i < len; i++) {
                    for (var j = 0, lenJ = $scope.purchaseBillList.length; j < lenJ; j++) {
                        if (selectedOrder[i].billId === $scope.purchaseBillList[j].billId) {
                            $scope.purchaseBillList[j].isChecked = true;
                            break;
                        }
                    }
                }
                $scope.markInfo.addAllChecked = checkAll("add");
            }

            function getPurchaseBill(curPage) {
                var service = "device";
                var reqUrl = "/purchaseRequest/list";
                var param = {};
                param.pageSize = $scope.billPageInfo.pageSize;
                if (!!curPage) {
                    $scope.billPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.billPageInfo.curPage;
                param.filters = {};
                param.filters.billNos = angular.copy($scope.orderCondition.billNos);
                param.filters.supplierOrgName = angular.copy($scope.orderCondition.supplierOrgName);
                param.filters.billStatus = "2";
                param.filters.seller = false;
                param.filters.inboundEnable = 1;
                param.filters.notDirect = 1;
                param.filters.sendStatus = 0;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate);
                    });
                    $scope.billPageInfo.totalRows = resp.value.total;
                    $scope.billPageInfo.totalPages = resp.value.pages;
                    $scope.purchaseBillList = resp.value.list;
                    checkRowSelected();
                });
            }

            $scope.orderSearch = function () {
                getPurchaseBill();
            };

            $scope.curSelectId = ''; // 只有单选的时候存在
            $scope.selBill = function (item, chooseType) {
                $scope.markInfo.allCheckedMaterial = false;
                var ids = [];
                $scope.curSelectId = '';
                if (chooseType === "batch" && !item) {
                    angular.forEach(selectedOrder, function (item) {
                        ids.push(item.billId)
                    })
                }

                if (chooseType === "single" && !!item) {
                    ids = [item.billId]
                    $scope.curSelectId = item.billId;
                }

                if (ids.length === 0) {
                    ybWidget.ShowMessage('请勾选采购订单');
                    return;
                }

                ybHttp.Post('device', '/purchaseRequest/getDetailByIds', ids).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    go2step2(resp.value);

                });
            };

            function setCurUserInfo4purchaseIn() {
                $scope.detailInfo.headerInfo.createId = $scope.curUser.userId;
                $scope.detailInfo.headerInfo.createName = $scope.curUser.name;
                $scope.detailInfo.headerInfo.deptId = $scope.curUser.deptId;
                $scope.detailInfo.headerInfo.deptName = $scope.curUser.deptName;
            }

            function go2step2(materialArr) {
                $scope.steps.curStep = 1;
                $scope.detailInfo.detailList = [];

                $scope.detailInfo.headerInfo = {
                    createDate: +new Date()
                };
                setCurUserInfo4purchaseIn();

                if ($scope.isWJ) {
                    $scope.detailInfo.headerInfo.warehouseCode = 'WJBJ'
                    $scope.detailInfo.headerInfo.inArea = '9000'
                    $scope.detailInfo.headerInfo.sapInArea = '9000'
                }

                angular.forEach(materialArr, function (item) {
                    if (item.qty > item.sendQty) {
                        var materielItem = {};
                        materielItem.purchaseRequestOrder = item.purchaseRequestOrder;
                        materielItem.materialNo = item.materialsNo;
                        materielItem.materialName = item.materialsDes;
                        materielItem.unit = item.unit;
                        materielItem.price = item.settlementPrice;
                        materielItem.qty = item.qty;
                        materielItem.rowNo = item.rowNo;
                        materielItem.sendQty = !!item.sendQty ? item.sendQty : 0;
                        materielItem.canInQty = ybWidget.Minus(item.qty, materielItem.sendQty);
                        materielItem.amount = item.inputQty || ybWidget.Minus(item.qty, materielItem.sendQty); // inputQty字段是批量导入新增操作时，excel中输入的数量
                        $scope.detailInfo.detailList.push(materielItem);
                    }
                });
            }

            $scope.delMateri = function (index) {
                $scope.detailInfo.detailList.splice(index, 1);
            };

            $scope.delData = function (delType, billId) {
                var service = "device";
                var reqUrl = "/purchaseInbound/remove";
                var billIds = [];

                if (delType === "single") {
                    billIds.push(billId);
                }

                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            billIds.push($scope.dataList[i].id);
                        }
                    }
                }

                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, billIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.detailInfo.detailList.length; i < len; i++) {
                    if (!!$scope.detailInfo.detailList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.detailInfo.detailList.length - 1; i >= 0; i--) {
                        if (!!$scope.detailInfo.detailList[i].isChecked && $scope.detailInfo.detailList[i].status != 2 && $scope.detailInfo.detailList[i].status != 3) {
                            $scope.detailInfo.detailList.splice(i, 1);
                        }
                    }
                    if ($scope.detailInfo.detailList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                });
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "(零件)",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseInbound/downloadPurchaseInboundMaterialExcel",
                    importReqService: "device",
                    importReqUrl: "/purchaseInbound/importExcelForPurchaseInbound",
                    importErrorUrl: "",
                    otherParams: {
                        purchaseId: $scope.curSelectId
                    }
                };
                ybWidget.ImportFile(param).then(function (data) {
                    go2step2(data);
                }).catch((err) => {
                    console.log(err);
                })
            };

            $scope.printBill = function ({ id, purchaseInboundOrder, isPrint }) {
                var param = {
                    billId: [id],
                    printType: "PurchaseIn",
                    recordPrint: {
                        billNo: purchaseInboundOrder
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function () {
                    if (!isPrint) {
                        getDataList();
                    }
                });
            };

            $scope.batchPrint = function () {
                var billIds = [];
                var billNos = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billIds.push($scope.dataList[i].id);
                        billNos.push($scope.dataList[i].purchaseInboundOrder);
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }

                var param = {
                    printType: "PurchaseIn",
                    cusInterface: '/purchaseInbound/batchPrintInfo',
                    cusParam: { billIds },
                    isBatchPrint: true,
                    recordPrint: {
                        billNo: billNos.join(','),
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function () {
                    getDataList();
                });
            };

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseUsingSelector().then(function (data) {
                    if (!!$scope.detailInfo.headerInfo.warehouseCode && (data.warehouseCode !== $scope.detailInfo.headerInfo.warehouseCode)) {
                        $scope.detailInfo.headerInfo.inArea = "";
                        $scope.detailInfo.headerInfo.sapInArea = "";
                    }
                    $scope.detailInfo.headerInfo.warehouseCode = data.warehouseCode;
                })
            };

            $scope.clearWarehouse = function () {
                $scope.detailInfo.headerInfo.warehouseCode = "";
                $scope.detailInfo.headerInfo.inArea = "";
                $scope.detailInfo.headerInfo.sapInArea = "";
            };

            $scope.selectArea = function () {
                if (!$scope.detailInfo.headerInfo.warehouseCode) {
                    ybWidget.ShowToaster('error', '请选择调入仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.detailInfo.headerInfo.warehouseCode;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.detailInfo.headerInfo.inArea = data.areaCode;
                    $scope.detailInfo.headerInfo.sapInArea = data.sapCode;
                })
            };

            $scope.clearArea = function () {
                $scope.detailInfo.headerInfo.inArea = "";
                $scope.detailInfo.headerInfo.sapInArea = "";
            };

            function getDetail(billId) {
                $scope.markInfoDetail = {
                    allChecked: false,
                    addAllChecked: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.selectedIds = [];
                var service = "device";
                var reqUrl = "/purchaseInbound/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.editData = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.detailInfo = data;

                    angular.forEach($scope.detailInfo.detailList, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                        item.lastAmount = item.amount;
                        item.canInQty = ybWidget.Plus(ybWidget.Minus(item.qty, item.sendQty), item.amount);
                    });
                    $scope.changeTab(2);
                })
            };

            function viewDetail(item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.detailList, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                        item.isChecked = false;
                    });
                    $scope.changeTab(3);
                })
            }

            $scope.checkQty = function (item) {
                item.deliveryQtyErr = false;
                if (item.amount === "") {
                    item.deliveryQtyErr = true;
                    item.deliveryQtyErrMsg = "入库数量不能为空";
                    return;
                }
                if (item.amount > 99999.999) {
                    item.amount = 99999.999;
                }
                if (parseFloat(item.amount) > parseFloat(item.canInQty)) {
                    item.deliveryQtyErr = true;
                    item.deliveryQtyErrMsg = "入库数量不能大于可入库数量";
                }
            };

            function checkListValid() {
                var isValid = true;
                for (var i = 0, len = $scope.detailInfo.detailList.length; i < len; i++) {
                    const item = $scope.detailInfo.detailList[i];
                    if ($scope.checkCaigouAmount(item, 'qty')) {
                        isValid = false;
                        break;
                    }
                    if ($scope.checkCaigouAmount(item, 'amount')) {
                        isValid = false;
                        break;
                    }

                    /* if ($scope.detailInfo.detailList[i].amount === "") {
                        isValid = false;
                        $scope.detailInfo.detailList[i].deliveryQtyErr = true;
                        $scope.detailInfo.detailList[i].deliveryQtyErrMsg = "入库数量不能为空";
                        break;
                    }
                    if (parseInt($scope.detailInfo.detailList[i].amount) > parseInt($scope.detailInfo.detailList[i].canInQty)) {
                        isValid = false;
                        $scope.detailInfo.detailList[i].deliveryQtyErr = true;
                        $scope.detailInfo.detailList[i].deliveryQtyErrMsg = "入库数量不能大于可入库数量";
                        break;
                    } */
                }
                return isValid;
            }

            $scope.mandatoryFinish = function (billNo, billId, item = {}) {
                const { materialNo, rowNo } = item;
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/purchaseInbound/manualFinish";
                    var param = {
                        billNo: billNo,
                        materialsNo: materialNo ? materialNo : null,
                        rowNo: rowNo ? rowNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!billId) {
                            getDetail(billId).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.detailInfo = data;
                                angular.forEach($scope.detailInfo.detailList, function (item) {
                                    item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                                });
                            });
                        }
                        getDataList();
                    });
                }, function () {
                });
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.detailInfo.detailList.length === 0) {
                    ybWidget.ShowToaster('error', '请选择零件');
                    return;
                }
                var listValid = checkListValid();
                if (!listValid) {
                    return;
                }
                var service = "device";
                var reqUrl = "/purchaseInbound/add";

                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/purchaseInbound/update";
                }
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };

            $scope.prevStep = function () {
                $scope.steps.curStep = 0;
            };

            $scope.inbound = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.detailList, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                        item.warehouseCode = data.headerInfo.warehouseCode;
                        item.areaCode = data.headerInfo.inArea;
                        item.locationCode = item.stockLocation; // 默认储位带出（需求号3802）
                    });
                    $scope.changeTab(4);
                });
            };

            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.detailInfo.headerInfo.warehouseCode
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };

            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };

            $scope.inboundSubmit = function () {
                /* if (true) {
                    UserContextService.BarcodeInbound($scope.detailInfo.detailList, 'purchaseInboundOrder', 'amount', 'status').then(() => {
                        $scope.changeTab(0);
                        getDataList();
                    })
                    return;
                } */
                // 以非条码入库
                notBarcodeInbound();
            };

            // 非条码入库
            function notBarcodeInbound() {
                var service = "device";
                var reqUrl = "/warehouseInboundRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                var errorCount = 0;
                param.headerInfo.businessOrder = $scope.detailInfo.headerInfo.purchaseInboundOrder;
                angular.forEach($scope.detailInfo.detailList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialNo;
                    listRow.warehouseCode = item.warehouseCode;
                    listRow.areaCode = item.areaCode;
                    listRow.locationCode = item.locationCode;
                    item.locationErr = false;
                    if ((item.status === 0 || item.status === 1) && !item.locationCode) {
                        item.locationErr = true;
                        errorCount++;
                    }
                    param.detailList.push(listRow);
                });
                if (errorCount > 0) {
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.isImportAdd = false;
            $scope.importAdd = function () {
                $scope.isImportAdd = true;

                var param = {
                    name: "(批量新增)",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseRequest/downloadNewExcel",
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/impNewExcel",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    go2step2(data);
                    $scope.changeTab(1);
                });
            };

            $scope.removeMaterial = function (id, idx) {
                var service = "device";
                var reqUrl = "/purchaseInbound/removeDetail";

                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, { id }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.detailInfo.detailList.splice(idx, 1);

                        if ($scope.detailInfo.detailList.length == 0) {
                            // 删完之后，跳转到列表页
                            $scope.changeTab(0);
                            getDataList();
                        }
                    });
                });
            };

            $scope.addBy = function() {
                setCurUserInfo4purchaseIn();
                $scope.detailInfo.headerInfo.createDate = new Date();
                $scope.changeTab(5);
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    if (!$scope.detailInfo.headerInfo.supplierOrgId) {
                        ybWidget.ShowToaster('error', '请选择供货商');
                        return;
                    }
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial", { supplierOrgId: $scope.detailInfo.headerInfo.supplierOrgId });
                    });
                }
            };

            $scope.importMaterielBy = function () {
                if (!$scope.detailInfo.headerInfo.supplierOrgId) {
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }

                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseInbound/download",
                    importReqService: "device",
                    importReqUrl: "/purchaseInbound/import",
                    importErrorUrl: "",
                    otherParams: {
                        supplierOrgId: $scope.detailInfo.headerInfo.supplierOrgId
                    }
                };
                ybWidget.ImportFile(param).then(function (data) {
                    $scope.detailInfo.detailList = [];
                    $scope.detailInfo.detailList = angular.copy(data);
                });
            };

            $scope.selectSold = function () {
                var param = {
                    name: "供货商",
                    type: "supplier",
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.headerInfo.supplierOrgId = data.platOrgId;
                    $scope.detailInfo.headerInfo.supplierOrgName = data.companyName;
                    clearMateriel();
                })
            };

            $scope.clearSold = function () {
                $scope.detailInfo.headerInfo.supplierOrgId = "";
                $scope.detailInfo.headerInfo.supplierOrgName = "";
                clearMateriel();
            };

            function clearMateriel() {
                $scope.detailInfo.detailList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $timeout(function () {
                    EventBus.Publish("clearMaterial");
                });
            }

            $scope.showErrTip = function (item, type, errTypes) {
                if (!!item[type+"EmptyErr"] || (errTypes && errTypes.some(et => !!item[type+et]))) {
                    item[type+"ShowErr"] = true
                }
            };

            $scope.hideErrTip = function (item, type) {
                item[type+"ShowErr"] = false
            };

            $scope.checkRequired = function (item, type) {
                if (!item[type] || item[type] == '0') {
                    item[type+"EmptyErr"] = true
                    item[type+"ShowErr"] = true
                } else {
                    item[type+"EmptyErr"] = false
                    item[type+"ShowErr"] = false
                }
                return item[type+"EmptyErr"]
            };

            function resetCaigouCheck(item) {
                item.qtyShowErr = false;
                item.qtyEmptyErr = false;
                item.qtyUnderErr = false;
            }
            $scope.checkCaigouAmount = function(item, type) {
                if ($scope.checkRequired(item, type)) {
                    item[type+"UnderErr"] = false;
                    return true;
                }

                if (Number(item[type]) < Number(item.amount)) {
                    item[type+"UnderErr"] = true;
                    item[type+"ShowErr"] = true;
                    return true;
                }
                item[type+"UnderErr"] = false;
                item[type+"ShowErr"] = false;
                resetRukuCheck(item);

                return false;
            };

            function resetRukuCheck(item) {
                item.amountShowErr = false;
                item.amountEmptyErr = false;
                item.amountExceedErr = false;
            }
            $scope.checkRukuAmount = function(item, type) {
                if ($scope.checkRequired(item, type)) {
                    item[type+"ExceedErr"] = false;
                    return true;
                }

                if (Number(item[type]) > Number(item.qty)) {
                    item[type+"ExceedErr"] = true;
                    item[type+"ShowErr"] = true;
                    return true;
                }
                item[type+"ExceedErr"] = false;
                item[type+"ShowErr"] = false;
                resetCaigouCheck(item);
                
                return false;
            };


            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
        ;
})(window, window.angular);
